<template>
  <div class="task">
    <el-card class="left-pannel">
      <el-form ref="formItem" :model="formItem" label-width="110px" size="small" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择客户" prop="custId">
              <el-select v-model="formItem.custId" clearable filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteCustMethod" @change="handleChange">
                <el-option v-for="item in custOption" :key="item.id" :label="item.name" :value="item.custId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择提货客户" prop="getCustId">
              <el-select v-model="formItem.getCustId" clearable filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteGetCustOptionMethod">
                <el-option v-for="item in getCustOption" :key="item.id" :label="item.name" :value="item.custId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择项目" prop="projectId">
              <el-select v-model="formItem.projectId" clearable filterable placeholder="先选客户,再选项目">
                <el-option v-for="item in projectOption" :key="item.id" :label="item.projectName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="提货车辆" prop="car">
              <el-select v-model="formItem.car" clearable filterable placeholder="先选客户" allow-create default-first-option>
                <el-option v-for="item in carOption" :key="item.id" :label="item.carNo" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择产品" prop="prodId">
              <el-select v-model="formItem.prodId" clearable filterable placeholder="请先选择客户，再选择产品" @change="handleProdChange">
                <el-option v-for="item in prodList" :key="item.id" :label="item.prodName" :value="item.prodId">
                  <span style="float: left">{{ item.prodName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.model }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="提货重量" prop="goodWeight">
              <el-input v-model="formItem.goodWeight" placeholder="请输入">
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="单价" prop="unitPrice">
              <el-input v-model="formItem.unitPrice" readonly></el-input>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24">
            <el-form-item label="应收金额" prop="receive">
              <el-input v-model="formItem.receive" readonly placeholder="点击计算预览数据">
                <el-button slot="append" icon="el-icon-school" @click="calcReceive">计算</el-button>
              </el-input>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24">
            <el-form-item label="已收金额" prop="received">
              <el-input v-model="formItem.received" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="未收金额" prop="unreceive">
              <el-input v-model="formItem.unreceive" readonly placeholder="点击计算预览数据">
                <el-button slot="append" icon="el-icon-school" @click="calcUnreceive">计算</el-button>
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="地磅员" prop="userId">
              <el-select v-model="formItem.userId" clearable filterable placeholder="请选择">
                <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="结算方式" prop="settleType">
              <el-select v-model="formItem.settleType" placeholder="请选择">
                <el-option label="信用" :value="1" />
                <el-option label="现结" :value="2" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="handleSubmit('formItem')">
          {{$route.query.id ? '修改交易订单' : '创建交易订单'}}
        </el-button>
      </div>
    </el-card>
    <el-card class="right-pannel">
      <el-descriptions title="客户基本信息" :column="3" size="medium" border :contentStyle="content_style" :label-style="label_style">
        <el-descriptions-item label="客户名称">{{curCust.name}}</el-descriptions-item>
        <el-descriptions-item label="客户编号">{{curCust.custId}}</el-descriptions-item>
        <el-descriptions-item label="客户简称">{{curCust.simpleNm}}</el-descriptions-item>
        <el-descriptions-item label="等级">{{RANK[curCust.rank]}}</el-descriptions-item>
        <el-descriptions-item label="付款方式">{{PAY_METHOD[curCust.payMethod] }}</el-descriptions-item>
        <el-descriptions-item label="结算方式">{{BALANCE[curCust.balance]}}</el-descriptions-item>
        <el-descriptions-item label="联络人">{{curCust.contact}}</el-descriptions-item>
        <el-descriptions-item label="联络电话1">{{curCust.phone1}}</el-descriptions-item>
        <el-descriptions-item label="联络电话2">{{curCust.phone2}}</el-descriptions-item>
        <el-descriptions-item label="授信额度">{{curCredit.creditQuota}}</el-descriptions-item>
        <el-descriptions-item label="已用额度">{{curCredit.usedCreditQuota}}</el-descriptions-item>
        <el-descriptions-item label="剩余额度">{{curCredit.availableCreditQuota}}</el-descriptions-item>
      </el-descriptions>
      <div style="height:10px"></div>
      <el-table :data="tableData" :height="tableHeight">
        <el-table-column prop="createTime" label="交易时间" width="160"></el-table-column>
        <el-table-column prop="tradeNo" label="交易单号" width="120"></el-table-column>
        <el-table-column prop="custName" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="getCustName" label="提货客户名称" width="180"></el-table-column>
        <el-table-column prop="projectName" label="项目名称" width="180"></el-table-column>
        <el-table-column prop="carNo" label="提货车辆" width="100"></el-table-column>
        <el-table-column prop="goodWeight" label="提货重量"></el-table-column>
        <el-table-column prop="prodName" label="产品名称" width="180"></el-table-column>
        <!-- <el-table-column prop="unitPrice" label="单价" width="100"></el-table-column> -->
        <!-- <el-table-column prop="receive" label="应收金额" width="100"></el-table-column> -->
        <!-- <el-table-column prop="received" label="已收金额" width="100"></el-table-column>
        <el-table-column prop="unreceive" label="未收金额" width="100"></el-table-column> -->
        <el-table-column prop="userName" label="地磅员"></el-table-column>
        <!-- <el-table-column prop="ifSettle" label="是否结算" width="80">
          <template slot-scope="scope">
            {{scope.row.ifSettle === 1 ? '已结算' : '未结算'}}
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="settleType" label="结算方式" width="80">
          <template slot-scope="scope">
            {{scope.row.settleType === 1 ? '信用' : '现结'}}
          </template>
        </el-table-column> -->
      </el-table>
    </el-card>

  </div>
</template>

<script>
import { getTenCust, getCustByCustId } from '@/api/cust'
import { getProjectList2 } from '@/api/project'
import { getCustProdList } from '@/api/prod'
import { getUserList } from '@/api/user'
import { getCreditByCustId } from '@/api/credit'
import { getCustStandard } from '@/api/standard'
import { addTrade, updateTrade, getTradeById, getTradeListByCustId } from '@/api/trade'
export default {
  data () {
    return {
      content_style: {
        'text-align': 'center',
        'min-width': '200px',
        'word-break': 'break-all'
      },
      label_style: {
        'text-align': 'center',
        'min-width': '100px',
        'word-break': 'keep-all'
      },
      RANK: {
        1: '信用',
        2: '现结'
      },
      PAY_METHOD: {
        1: '银行转账',
        2: '银行承兑'
      },
      BALANCE: {
        1: '信用',
        2: '现结'
      },
      formItem: {
        custId: '',
        getCustId: '',
        projectId: '',
        goodWeight: '',
        unitPrice: '',
        receive: '',
        received: 0,
        unreceive: '',
        userId: '',
        car: '',
        carNo: '',
        // settleType: 1,
        // ifSettle: 2
      },
      tableData: [],
      activeName: '1',
      custOption: [],
      getCustOption: [],
      projectOption: [],
      projectList: [],
      prodList: [],
      userList: [],
      carOption: [],
      curCust: {},
      curCredit: {},
      rules: {
        custId: [{ required: true, message: '请选择客户', trigger: 'blur' }],
        // getCustId: [{ required: true, message: '请选择客户', trigger: 'blur' }],
        // projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        prodId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择', trigger: 'blur' }],
        GoodWeight: [{ required: true, message: '请输入', trigger: 'blur' }],
      }
    }
  },
  created () {
    this.queryUserList()
    if (this.$route.query.id) {
      this.queryTrade(this.$route.query.id)
    } else {
      // 这么写解决project解决回显问题
      this.queryProject()
    }
  },
  computed: {
    tableHeight () {
      // const pagination = 60
      const condition = 270
      const pagePadding = 40
      const header = 60
      return window.innerHeight - condition - pagePadding - header
    },
  },
  methods: {
    async queryTrade (id) {
      const res = await getTradeById(id)
      if (res.code === 200) {
        this.formItem = { ...res.data }
        this.custOption = [{ name: this.formItem.custName, custId: this.formItem.custId }]
        this.getCustOption = [{ name: this.formItem.getCustName, custId: this.formItem.getCustId }]
        this.prodList = [{ prodName: this.formItem.prodName, prodId: this.formItem.prodId }]
        this.projectOption = [{ projectName: this.formItem.projectName, id: this.formItem.projectId }]
        this.queryCust(this.formItem.custId)
        this.queryProd(this.formItem.custId)
        this.queryList(this.formItem.custId)
        this.queryCreditByCustId(this.formItem.custId)
        this.queryCustStandard(this.formItem.custId)
        this.queryProject()
      } else {
        this.formItem = {}
        this.curCredit = {}
        this.curCust = {}
        this.projectOption = [];
        this.prodList = []
        this.carOption = []
      }
    },
    async queryCreditByCustId (custId) {
      const res = await getCreditByCustId(custId)
      if (res.code === 200) {
        this.curCredit = res.data
      } else {
        this.curCredit = {}
      }
    },
    async queryCustStandard (custId) {
      const res = await getCustStandard(custId)
      if (res.code === 200) {
        this.carOption = res.data
      } else {
        this.carOption = []
      }
    },
    async queryUserList () {
      const res = await getUserList()
      if (res.code === 200) {
        this.userList = res.data
        this.formItem.userId = this.$store.getters.getUser.userId
      } else {
        this.userList = []
        this.$message.error(res.msg)
      }
    },
    async queryProject () {
      const res = await getProjectList2()
      if (res.code === 200) {
        this.projectList = res.data
        if (this.formItem.custId) {
          this.makeProjects(this.formItem.custId)
        }
      } else {
        this.projectList = []
        this.$message.error(res.msg)
      }
    },
    async queryList () {
      const res = await getTradeListByCustId(this.formItem.custId)
      if (res.code === 200) {
        this.tableData = res.data
      } else {
        this.tableData = []
        this.$message.error(res.msg)
      }
    },
    async queryProd () {
      const res = await getCustProdList(this.formItem.custId)
      if (res.code === 200) {
        this.prodList = res.data.filter(d => d.ifUse === 1)
      } else {
        this.prodList = []
        this.$message.error(res.msg)
      }
    },
    async queryCust (custId) {
      const res = await getCustByCustId(custId)
      if (res.code == 200) {
        this.curCust = res.data
      } else {
        this.curCust = {}
        this.$message.error(res.msg)
      }
    },
    async remoteCustMethod (keyword) {
      if (keyword) {
        const res = await getTenCust({ keyword })
        if (res.code === 200) {
          this.custOption = res.data
        } else {
          this.custOption = []
        }
      } else {
        this.custOption = [];
        this.$message.error(res.msg)
      }
    },
    async remoteGetCustOptionMethod (keyword) {
      if (keyword) {
        const res = await getTenCust({ keyword })
        if (res.code === 200) {
          this.getCustOption = res.data
        } else {
          this.getCustOption = []
          this.$message.error(res.msg)
        }
      } else {
        this.getCustOption = [];
      }
    },
    calcUnreceive () {
      const { receive, received } = this.formItem
      this.formItem.unreceive = Math.round((Number(receive) - Number(received)) * 100) / 100;
    },
    calcReceive () {
      const { unitPrice, goodWeight } = this.formItem
      this.formItem.receive = Math.round((Number(unitPrice) * Number(goodWeight)) * 100) / 100;
    },
    makeProjects (custId) {
      const arr = this.projectList.filter(p => p.ifUse === 1)
      const arr1 = arr.filter(a1 => a1.custId === custId)
      const arr2 = arr.filter(a2 => !a2.custId)
      this.projectOption = arr1.length > 0 ? arr1 : arr2
    },
    handleChange (custId) {
      if (custId) {
        this.queryCust(custId)
        this.makeProjects(custId)
        this.queryProd(custId)
        this.queryList(custId)
        this.queryCreditByCustId(custId)
        this.queryCustStandard(custId)
      } else {
        this.projectOption = [];
        this.prodList = []
        this.tableData = []
        this.curCust = {}
        this.curCredit = {}
        this.carOption = []
      }
    },
    handleProdChange (prodId) {
      if (prodId) {
        const prod = this.prodList.find(p => p.prodId === prodId)
        this.formItem.unitPrice = prod.unitPrice
      } else {
        this.formItem.unitPrice = null
      }
    },
    handleSubmit (formName) {
      const CAR = this.carOption.find(c=>c.id===this.formItem.car)
      if(!CAR) {
        this.formItem.carNo = this.formItem.car
        this.formItem.car = null
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = this.formItem.tradeNo ? await updateTrade(this.formItem) : await addTrade(this.formItem)
          if (res.code === 200) {
            this.$emit('ok')
            this.$router.push('/trade')
          } else {
            this.$message.error(res.msg)
          }
        }
      })
    }
  }

}
</script>
<style lang="less" scoped>
.task {
  height: 100%;
  display: flex;
  .left-pannel {
    flex: 1;
    height: 100%;
  }
  .right-pannel {
    flex: 3;
    margin-left: 20px;
    // display: flex;
    // flex-direction: column;
  }
  .el-select {
    width: 100%;
  }
  // ::v-deep(.el-descriptions-item__label) {
  //   width: 150px; /* 或者你需要的固定宽度 */
  //   max-width: 150px; /* 防止宽度超过你设定的最大宽度 */
  // }
  ::v-deep(.el-card__body) {
    height: calc(100% - 40px);
  }
}
</style>